package com.cys.dm.rabbitService;

import com.cys.dm.client.order.DmOrderClient;
import com.cys.dm.client.scheduler.DmSchedulerSeatClient;
import com.cys.dm.entity.scheduler.DmSchedulerSeat;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author blue_t
 * @date 2021-01-17 18:47
 * 消费延时队列消息
 */
@Component
public class MesageReceiver {
    @Resource
    private DmSchedulerSeatClient dmSchedulerSeatClient;
    @Resource
    private DmOrderClient dmOrderClient;

    /**
     * 监听转发队列  走逻辑判断，尚未支付且超过过期时间的订单号设置为失效订单
     * @param message 信息包装类
     * @param channel 通道
     */
    @RabbitListener(queues = {"ORDER_REDIRECT_QUEUE"})
    public void redirect(Message message, Channel channel) throws IOException {
        // 从队列中取出订单号
        byte[] body = message.getBody();
        String orderNo = new String(body,"UTF-8");
        System.out.println(new Date() +  "消费消息，订单号为" + orderNo);
        List<DmSchedulerSeat> byOrderNos = dmSchedulerSeatClient.findSchedulerSeatByOrderNo(orderNo);
        // 状态不等于==已售出==修改状态
        byOrderNos.forEach(byOrderNo ->{
            if (byOrderNo.getStatus() != 3){
                DmSchedulerSeat dmSchedulerSeat = new DmSchedulerSeat();
                dmSchedulerSeat.setOrderNo(orderNo);
                dmSchedulerSeat.setStatus(1);
                dmSchedulerSeatClient.updSeatStatus(dmSchedulerSeat);
                // 修改订单状态为 -1 支付已取消
                dmOrderClient.updataOrderType(orderNo,-1);
            }
        });
        // 确认消息有没有被收到,false表示手动确认  在处理完消息时，返回应答状态
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
